package com.spark.colliery.module.home.fragment

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.animation.Animation
import android.widget.ImageView
import com.blankj.utilcode.util.LogUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.jakewharton.rxbinding2.view.RxView
import com.labo.kaji.fragmentanimations.CubeAnimation
import com.spark.colliery.R
import com.spark.colliery.module.home.model.BannerItemModel
import com.spark.colliery.module.home.model.HomeOptionListModel
import com.spark.colliery.module.home.model.NewsItemModel
import com.spark.colliery.module.home.model.VertBannerModel
import com.spark.common.BaseFragment
import com.spark.common.Const
import com.spark.common.ext.*
import com.spark.common.net.Http
import com.spark.common.net.toJsonBody
import com.spark.common.ui.WebActivity
import com.spark.data.FileTransferFragment
import com.spark.data.MaterialRetrievalFragment
import com.taobao.library.BaseBannerAdapter
import com.taobao.library.VerticalBannerView
import com.youth.banner.BannerConfig
import com.youth.banner.loader.ImageLoaderInterface
import kotlinx.android.synthetic.main.frag_home_common.*
import me.yokeyword.fragmentation.SupportFragment
import java.util.*
import java.util.concurrent.TimeUnit

/**
 * 普通界面
 */
class HomeCommonFragment : BaseFragment() {
    override fun contentResId(): Int {
        return R.layout.frag_home_common
    }

    private var launchTime = 0

    private var onSwitchListener: OnSwitchListener? = null

    private val bannerUrlList = ArrayList<String>()
    private val bannerTitleList = ArrayList<String>()
    private val bannerList = ArrayList<BannerItemModel>()

    private lateinit var homeOptionAdapter: HomeOptionsAdapter
    private lateinit var homeNewsAdapter: HomeNewsAdapter

    companion object {
        fun newInstance(): HomeCommonFragment {
            val args = Bundle()
            val fragment = HomeCommonFragment()
            fragment.arguments = args
            return fragment
        }
    }

    @SuppressLint("CheckResult")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        RxView.clicks(ll_home_more)
                .throttleFirst(800, TimeUnit.MILLISECONDS)
                .subscribe { o ->
                    if (onSwitchListener != null) {
                        onSwitchListener!!.switchToAdmin()
                    }
                }

        initHomeOptions()
        initHomeNews()
        initBanner()
        /**
         * vertical banner task track
         */
        val vertBanners = mutableListOf<VertBannerModel>()
        vertBanners.add(VertBannerModel())
        val vertBannerAdapter = VertBannerAdapter(vertBanners)
        vert_banner.setAdapter(vertBannerAdapter)
        vert_banner.setOnClickListener {
            alert("功能开发中，敬请期待!")
        }
    }


    override fun onResume() {
        super.onResume()
        // 统计启动次数
        launchTime++
    }

    override fun onSupportVisible() {
        super.onSupportVisible()
        vert_banner.start()
    }

    override fun onSupportInvisible() {
        super.onSupportInvisible()
        vert_banner.stop()
    }

    /**
     * Fragment 跳转动画
     *
     * @param transit
     * @param enter
     * @param nextAnim
     * @return
     */
    override fun onCreateAnimation(transit: Int, enter: Boolean, nextAnim: Int): Animation? {
        return if (launchTime <= 0) {
            null
        } else CubeAnimation.create(CubeAnimation.LEFT, enter, 300)
    }

    /**
     * 从首页切换到管理
     */
    @SuppressLint("CheckResult")
    private fun switchAdmin() {
        childFragmentManager
                .beginTransaction()
                //.setCustomAnimations(R.anim.ack_3d_enter, R.anim.ack_3d_exit, R.anim.ck_3d_enter, R.anim.ck_3d_exit)
                .replace(R.id.fl_content, com.spark.colliery.module.home.fragment.HomeAdminManagerFragment.newInstance())
                .addToBackStack(com.spark.colliery.module.home.fragment.HomeAdminManagerFragment::class.java.simpleName)
                .commit()
    }

    private fun initHomeOptions() {
        homeOptionAdapter = HomeOptionsAdapter(R.layout.item_home_options)
        val gridLayoutManager = object : GridLayoutManager(context, 5, GridLayoutManager.VERTICAL, false) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        recy_home_options.adapter = homeOptionAdapter
        recy_home_options.layoutManager = gridLayoutManager
        // fake data
        homeOptionAdapter.addData(mutableListOf(
                HomeOptionListModel.ResultMap(imgurl = activity?.realPath(R.drawable.btn_home_options_material)
                        ?: "", modelId = "2-1", title = "资料检索"),
                HomeOptionListModel.ResultMap(imgurl = activity?.realPath(R.drawable.btn_home_options_xieshang)
                        ?: "", modelId = "2-2", title = "文件传输")
        ))

        homeOptionAdapter.setOnItemClickListener { adapter, view, position ->
            val data = homeOptionAdapter.data[position]
            when (data.modelId) {
                // 资料检索
                "2-1" -> {
                    parentFragment?.parentFragment?.let { it as SupportFragment }?.start(MaterialRetrievalFragment.newInstance())
                }
                // 文件传输
                "2-2" -> {
                    parentFragment?.parentFragment?.let { it as SupportFragment }?.start(FileTransferFragment.newInstance())
                }
            }
        }
        fetchHomeOptions()
    }

    private fun initHomeNews() {
        val homeNewsAdapter = HomeNewsAdapter(R.layout.item_home_new)
        val linearLayoutManager = object : LinearLayoutManager(context) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        recy_home_news.adapter = homeNewsAdapter
        recy_home_news.layoutManager = linearLayoutManager

        homeNewsAdapter.setNewData(NewsItemModel.generateData())
        homeNewsAdapter.setOnItemClickListener { adapter, view, position ->
            activity?.apply {
                WebActivity.actionStart(this, "新闻详情", "http://www.nea.gov.cn/ztzl/mtscnlgg/index.htm")
            }
        }
    }

    private fun initBanner() {
        /**
         * horizontal banner
         */
        for (i in 0..2) {
            bannerList.add(BannerItemModel("http://p4w29og7z.bkt.clouddn.com/%E5%9B%BE%E5%B1%82%201.png", i.toString()))
        }
        bannerUrlList.add("http://p4w29og7z.bkt.clouddn.com/%E5%9B%BE%E5%B1%82%201.png")
        // bannerUrlList.add("http://p4w29og7z.bkt.clouddn.com/%E5%9B%BE%E5%B1%82%201.png")
        // bannerUrlList.add("http://p4w29og7z.bkt.clouddn.com/%E5%9B%BE%E5%B1%82%201.png")

        bannerTitleList.add("1")
        bannerTitleList.add("2")
        bannerTitleList.add("3")

        banner_main.setBannerStyle(BannerConfig.NOT_INDICATOR)
        //设置图片加载器
        banner_main.setImageLoader(object : ImageLoaderInterface<ImageView> {
            override fun createImageView(context: Context?): ImageView {
                return ImageView(context)
            }

            override fun displayImage(context: Context?, path: Any?, imageView: ImageView?) {
                if (path is String)
                    imageView?.server(path)
            }
        })
        //设置图片集合
        banner_main.setImages(bannerUrlList)
        //设置banner动画效果
        //bannerMain.setBannerAnimation(Transformer.ScaleInOut);
        //设置标题集合（当banner样式有显示title时）
        banner_main.setBannerTitles(bannerTitleList)
        //设置自动轮播，默认为true
        banner_main.isAutoPlay(true)
        //设置轮播时间
        banner_main.setDelayTime(5000)
        banner_main.setOnBannerListener {
            alert("功能开发中，敬请期待!")
        }
        //设置指示器位置（当banner模式中有指示器时）
        //banner.setIndicatorGravity(BannerConfig.RIGHT);
        //banner设置方法全部调用完毕时最后调用
        banner_main.start()
    }

    interface OnSwitchListener {
        fun switchToAdmin()
    }

    fun setOnSwtichListener(listener: OnSwitchListener?) {
        if (listener == null) {
            return
        }
        onSwitchListener = listener
    }

    /**
     * 获取首页选项
     */
    @SuppressLint("CheckResult")
    fun fetchHomeOptions() {
        Http.request()
                .rxPost("${Const.base_url}${Const.act_home_opt}", "{}".toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            Gson().fromJson(it, HomeOptionListModel::class.java)?.apply {
                                if (code == "200") {
                                    homeOptionAdapter.addData(resultMaps)
                                } else {
                                    error(msg)
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            LogUtils.e(it.message)
                        },
                        {},
                        {}
                )
    }

    /**
     * @param appshow app 是否显示图片
     *        - 1 显示
     *        - 不设置，全部显示
     *
     */
    @SuppressLint("CheckResult")
    private fun fetchNotices(page: Int) {
        val params = mutableMapOf("page" to "$page", "pageSize" to "10")
        Http.request()
                .rxPost("${Const.base_url}${Const.act_home_noticelist}", params.toJsonBody())
                .wrapIO()
                .subscribe(
                        {

                        },
                        {
                            it.printStackTrace()
                            report(it)
                        },
                        {},
                        {
                            dispose = it
                        }
                )
    }
}

/**
 * 新闻
 */
class HomeNewsAdapter(layoutResId: Int) : BaseQuickAdapter<NewsItemModel, BaseViewHolder>(layoutResId) {

    override fun convert(helper: BaseViewHolder, item: NewsItemModel) {
        val type = item.type
        if (type == 0) {
            helper.getView<View>(R.id.rl_news_type).visibility = View.VISIBLE
        } else if (type == 1) {
            helper.getView<View>(R.id.rl_news_type).visibility = View.GONE
        }

        helper.setText(R.id.tv_news_title, item.title)
        helper.setText(R.id.tv_news_content, item.content)
        helper.setText(R.id.tv_news_readed, item.readed.toString())
        helper.setText(R.id.tv_news_date, item.date)
        if (helper.adapterPosition == data.size - 1) {
            helper.setGone(R.id.news_divider, false)
        }

    }
}

/**
 * 选项
 */
class HomeOptionsAdapter(layoutResId: Int) : BaseQuickAdapter<com.spark.colliery.module.home.model.HomeOptionListModel.ResultMap, BaseViewHolder>(layoutResId) {
    override fun convert(helper: BaseViewHolder, item: com.spark.colliery.module.home.model.HomeOptionListModel.ResultMap) {
        helper.apply {
            getView<ImageView>(R.id.iv_home_option).server(item.imgurl)
            setText(R.id.tv_home_option, item.title)
        }
    }
}

/**
 * VerticalBannerAdapter
 */
class VertBannerAdapter(var datas: MutableList<VertBannerModel>) : BaseBannerAdapter<VertBannerModel>(datas) {
    override fun setItem(p0: View?, p1: VertBannerModel?) {

    }

    override fun getView(p0: VerticalBannerView?): View {
        return LayoutInflater.from(p0!!.context).inflate(R.layout.item_task_track, null)
    }


}